import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { ScrollView, View, Image } from '@tarojs/components'
import { AtMessage, AtActivityIndicator, AtDivider } from 'taro-ui'
import classnames from 'classnames'
import { connect } from 'react-redux'
import './index.scss'
import { delayQuerySelector, throttle } from '@/utils'
import { getplatformList } from '@/api/annual'
import { storeInfo } from '@/api'
@connect<any>(({ car }) => ({
  car: car.carInfo.currentCar,
}))
export default class AnnualIndex extends Component<any, any> {
  $instance = getCurrentInstance();
  protected bannerH: number
  protected bannerImg: string = `${SOURCES_PATH}/img/annual/banner.png`
  constructor (props) {
    super(props)
    this.state = {
      isFix: false,
      scrollTop: 0,
      lock: false,
      page: 1,
      typePage: {
        onePage: 1,
        twoPage: 1,
        threePage: 1
      },
      tips: false,
      recommonedCards: [],
      maintainCards: [],
      beautyCards: [],
      selectIndex: 0,
      typeOptios: [
        { type: 1, typeLabel: '店长推荐', lock: false, page: 1, data: [] },
        { type: 2, typeLabel: '美容保养卡', lock: false, page: 1, data: [] },
        { type: 3, typeLabel: '美容卡', lock: false, page: 1, data: [] }
      ]
    }
  }
  static options = {
    addGlobalClass: true
  }

  handleClick(item) {
    console.log(item)
    Taro.navigateTo({
      url: `/pages/detection/detail/index?reportId=${item.reportId}&title=${item.typeLabel}`
    })
  }
  onScroll = throttle(e => {
    this.setFixStatus(e.detail.scrollTop)
  }, 50)

  // 下拉请求开关控制
  private isGet: boolean = true

  onScrollToLower() {
    let { typeOptios, selectIndex } = this.state
    let lock = typeOptios[selectIndex].lock
    if (!lock) {

      console.log('isGet: ', this.isGet);
      if (this.isGet) {
        this.isGet = false
        typeOptios[selectIndex].page++
        this.setState({
          typeOptios
        }, () => {
          this.getList()
        })
      }
    }
  }

  handleChangeNavIndx(index: number) {
    let { selectIndex, isFix } = this.state
    console.log('isFix', isFix)
    if (isFix) {
      this.setState({
        scrollTop: 0
      }, () => {
        this.setState({
          scrollTop: this.bannerH
        }, () => {

        })
      })
    }
    this.setState({
      selectIndex: index
    }, () => {
      console.log('selectIndex', selectIndex, 'index', index)
      if (selectIndex !== index) {
        console.log('执行---getList')
        this.getList()
      }
    })
  }

  UNSAFE_componentWillMount() {
    delayQuerySelector(this, '.banner-wrap', 0).then(rect => {
      if (rect[0]) {
        console.log(rect[0].height)
        this.bannerH = rect[0].height
      }
    })
  }

  async componentDidMount() {
    let city = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
    console.log('this.props', this.props)
    let { cityCode = '', storeCode = '' } = this.$instance.router.params
    console.log('this.$instance.router.params', this.$instance.router.params)
    if (storeCode) {
      let storeParams: any = {
        storeCode
      }
      const result = await storeInfo(storeParams)
      const data = result.data['data']
      console.log('data')
      if (data.cityCode !== city.adCode) {
        this.setState({
          tips: true
        })
      }
    }
    if (cityCode) {
      if (cityCode !== city.adCode) {
        this.setState({
          tips: true
        })
      }
    }
    this.getList()
  }

  async getList() {
    let { cityCode = '', storeCode = '' } = this.$instance.router.params
    let { typeOptios, selectIndex } = this.state
    let perPage = 20
    let page = typeOptios[selectIndex].page
    let selectType = typeOptios[selectIndex].type
    let lock = typeOptios[selectIndex].lock
    console.log('进来getList', typeOptios)
    console.log('lock', lock)
    let params = {
      position: selectType,
    }
    let query = {
      filter: {
        and: [params]
      },
      perPage,
      page: page
    }
    let paramsData = {
      query
    }
    if (storeCode) paramsData.storeCode = storeCode
    if (cityCode) paramsData.cityCode = cityCode
    if (lock) return
    getplatformList(paramsData).then(res => {
      console.log('res', res)
      // console.log(res.data.data)
      let data = res.data.data
      if (data.length < perPage) {
        lock = true
      }
      typeOptios[selectIndex].lock = lock
      typeOptios[selectIndex].data = [...typeOptios[selectIndex].data, ...data]
      this.setState({
        typeOptios
      })
    }).catch(err => {
      console.log('err', err)
    }).finally(() => {
      this.isGet = true
    })

  }

  setFixStatus(scrollTop: number) {
    let newIsFix: boolean = false
    let { isFix } = this.state
    if (scrollTop > this.bannerH) {
      newIsFix = true
    }
    if (isFix !== newIsFix) {
      this.setState({
        isFix: newIsFix
      })
    }
  }

  handleToPath() {
    const { car } = this.props
    if (car) {
      Taro.navigateTo({
        url: '/pages/annual/diy/index'
      })
    } else {
      Taro.navigateTo({
        url: '/pages/car/add/index'
      })
    }
  }
  // 去订单确认
  toCreateOrder(annualCardId) {
    const { car } = this.props
    let { cityCode = '', storeCode = '' } = this.$instance.router.params
    console.log('car', car)
    console.log('有没有执行到', this.$instance.router.params)
    if (car) {
      Taro.navigateTo({
        url: `/pages/order/index/index?type=1&annualCardId=${annualCardId}&cityCode=${cityCode}&storeCode=${storeCode}`
      })
    } else {
      Taro.navigateTo({
        url: '/pages/car/add/index'
      })
    }
  }
  render() {
    const scrollStyle = {
      height: '100vh'
    }
    let { isFix, scrollTop, selectIndex, typeOptios, tips } = this.state
    let { cityCode = '', storeCode = '' } = this.$instance.router.params
    let selectType = typeOptios[selectIndex].type
    let lowerThreshold = 50
    console.log('typeOptios[selectIndex].data', typeOptios[selectIndex].data)
    console.log('typeOptios[selectIndex]', typeOptios[selectIndex])
    return (
      <View className='annual-index-wrap'>
        <ScrollView className='list' lowerThreshold={lowerThreshold} onScrollToLower={this.onScrollToLower.bind(this)} enableBackToTop scrollTop={scrollTop} scrollY onScroll={this.onScroll.bind(this)} style={scrollStyle}>
          <View className='banner-wrap'>
            <Image className='img' mode='scaleToFill' src={this.bannerImg}></Image>
            {/* {
							!cityCode && !storeCode ? <View className='annual-tips'>全门店通用</View> : <View className='annual-tips'>全城门店通用</View>
						} */}
            <View className='btn' onClick={this.handleToPath.bind(this)}>马上定制</View>
          </View>
          <View className={
            classnames('narbar-wrap', {
              'fix': isFix
            })
          }
          >
            {typeOptios.map((item, index) =>
              <View className={
                classnames('item', {
                  'active': item.type === selectType
                })
              } onClick={this.handleChangeNavIndx.bind(this, index)} key={String(index)}
              >
                {item.typeLabel}
              </View>
            )}
          </View>
          <View className={
            classnames('content-wrap', {
              'padding': isFix
            })
          }
          >
            {
              tips ? <View className='diff-city--tips'>您当前选择的城市可能与年卡适用城市不一致，下单时请注意可用地区及门店</View> : null
            }
            {
              typeOptios[selectIndex].data.map((item) =>
                <View className='item' onClick={() => this.toCreateOrder(item.id)} key={item.id}>
                  <Image className='annual-img' mode='aspectFill' lazyLoad src={item.image}></Image>
                </View>
              )
            }
            {
              !typeOptios[selectIndex].lock && <View className='loading-animation'>
                <AtActivityIndicator mode='center' size={54} color='##12B3FF'></AtActivityIndicator>
              </View>
            }
            {typeOptios[selectIndex].lock && <AtDivider content='我是有底线的～' fontColor='#ccc' lineColor="#f5f5f5" />}
          </View>
        </ScrollView>
        <AtMessage />
      </View>
    )
  }
}
